package com.mmren.edu.dtx.service;

import com.mmren.edu.common.result.CommonResult;
import com.mmren.edu.dtx.client.StockClient;
import com.mmren.edu.dtx.domain.Order;
import com.mmren.edu.dtx.mapper.OrderMapper;
import com.mmren.edu.dtx.mapper.ProductItemMapper;
import com.mmren.edu.dtx.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Random;

/**
 * 欢迎来到牧码人教育，做Java我们是专业的
 *
 * @创建人： 牧码人教育-Gerry
 * @创建时间： 2020-4-20
 * @功能描述：
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductItemMapper itemMapper;
    @Autowired(required = false)
    private StockClient stockClient;

    @Transactional
    @Override
    public boolean saveOrder(OrderVO vo) {
        // 远程调用库存服务减库存
        CommonResult result = stockClient.reduceStock(vo);
        if (result.getCode() == 201) {
            throw new RuntimeException("远程调用库存服务出现问题....");
        }

        // 生成订单
        // 1、 根据商品ID获取商品单价
        BigDecimal unitPrice = itemMapper.selectUnitPriceByProductId(vo.getProductId());
        // 2、获取订单支付金额
        BigDecimal paymentAmount = unitPrice.multiply(new BigDecimal(vo.getAmount()));
        // 3、 创建订单对象
        Order order = Order.builder().orderId(System.nanoTime())
                .paymentAmount(paymentAmount)
                .productId(vo.getProductId())
                .state(new Random().nextInt(2))
                .userId(System.currentTimeMillis())
                .build();
        boolean flag = orderMapper.insertOrderInfo(order) > 0;
        return flag;
    }
}
